package StudyCode.summary.csv;

import java.util.ArrayList;
import java.util.List;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ConvertsCSVLineStringArray {
	protected static final char FIELD_SEPARATOR = ',';
	protected static final char FIELD_QUOTE = '"';
	protected static final String DOUBLE_QUOTE = "\"\"";

	public static String[] toStringArray(String line) {
		List<String> row = new ArrayList<String>();

		boolean inQuotedField = false;
		int fieldStart = 0;

		final int len = line.length();
		for (int i = 0; i < len; i++) {
			char c = line.charAt(i);
			if (c == FIELD_SEPARATOR) {
				if (!inQuotedField) {
					addField(row, line, fieldStart, i, inQuotedField);
					fieldStart = i + 1;
				}
			} else if (c == FIELD_QUOTE) {
				if (inQuotedField) {
					if (i + 1 == len
							|| line.charAt(i + 1) == FIELD_SEPARATOR) {
						addField(row, line, fieldStart, i, inQuotedField);
						fieldStart = i + 2;
						i++;
						inQuotedField = false;
					}
				} else if (fieldStart == i) {
					inQuotedField = true;
					fieldStart++;
				}
			}
		}
		if (len > 0 && fieldStart <= len) {
			addField(row, line, fieldStart, len, inQuotedField);
		}
		return row.toArray(new String[row.size()]);
	}

	private static void addField(List<String> row, String line,
	                             int startIndex, int endIndex, boolean inQuoted) {
		String field = line.substring(startIndex, endIndex);
		if (inQuoted) {
			field = field.replace(DOUBLE_QUOTE, "\"");
		}
		row.add(field);
	}
}
